﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using MadeInPortugal.Class;

namespace MadeInPortugalWebApplication
{

        public partial class blackList : System.Web.UI.Page
    {
        bool[] rowChanged;
        bool[] rowDeleted;

        BlackList _srv = new BlackList();
        ArrayList blackListSource = new ArrayList();
        DataTable dtPages;

        public int CurrentPage
        {
            get { return int.Parse(hfPageNumber.Value); }
            set { hfPageNumber.Value = value.ToString(); ; }
        }

        public int PageSize
        {
            get;
            set;
        }

        public DataTable DtPages
        {
            get
            {
                if (dtPages == null)
                {
                    dtPages = new DataTable();
                    dtPages.Columns.Add("Class");
                    dtPages.Columns.Add("PageNumber");
                }
                return dtPages;
            }
            set
            {
                if (value != null)
                    dtPages = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageSize = 10;
            if (!IsPostBack)
            {
                int UserId = 0;
                String UserType;
                if (Session["UserType"] == null)
                    Response.Redirect("index.aspx");
                if (Session["UserId"] == null)
                    Response.Redirect("index.aspx");
                UserType = Session["UserType"].ToString();
                int.TryParse(Session["UserId"].ToString(), out UserId);
                if (UserType != "Admin")
                    Response.Redirect("index.aspx");

                GetAllBlacklistTerms();
                FillBlacklistTermsPages();
            }
            else
            {
                blackListSource = (ArrayList)Session["userlist"];
            }

            DtPages = (DataTable)ViewState["pages"];


        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            int totalRows = blacklistGridView.Rows.Count;
            rowChanged = new bool[totalRows];
            rowDeleted = new bool[totalRows];

            BuildPagination();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (Page.IsPostBack)
            {
                int totalRows = blacklistGridView.Rows.Count;
                for (int r = 0; r < totalRows; r++)
                {
                    if (rowChanged[r])
                    {
                        GridViewRow thisGridViewRow = blacklistGridView.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbNumber");
                        TextBox tbxTerm = (TextBox)thisGridViewRow.FindControl("tbxTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            BlackList updated = _srv.Update(new BlackList() { ID = pk, Term = tbxTerm.Text.Trim() });

                            if (updated != null)
                            {
                                SetFeedBack(string.Format("O termo '{0}' foi actualizado com sucesso.", updated.Term), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao actualizar o termo '{0}'.", updated.Term), Messages.FeedBackType.error);
                            }
                        }
                        GetAllBlacklistTerms();
                        // Only one row afected by postback
                        break;
                    }
                    if (rowDeleted[r])
                    {
                        GridViewRow thisGridViewRow = blacklistGridView.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbNumber");
                        Label lbTerm = (Label)thisGridViewRow.FindControl("lbTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            BlackList updated = _srv.Delete(new BlackList() { ID = pk, Term = lbTerm.Text.Trim() });

                            if (updated != null)
                            {
                                SetFeedBack(string.Format("O termo '{0}' foi eliminado com sucesso.", updated.Term), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao eliminar o termo '{0}'.", updated.Term), Messages.FeedBackType.error);
                            }
                        }
                        GetAllBlacklistTerms();
                        // Only one row afected by postback
                        break;
                    }
                }
            }

            FillBlacklistTermsPages();

            BuildPagination();

            ViewState["pages"] = DtPages;
            Session["userlist"] = blackListSource;
        }

        protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("deleteBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    rowDeleted[row] = true;
            }
            if (e.CommandName.Equals("saveBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    rowChanged[row] = true;
            }
        }
        
        protected void SaveNewTerm_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbxNewTerm.Text))
            {
                BlackList inserted = _srv.Create(new BlackList() { Term = tbxNewTerm.Text.Trim() });

                if (inserted != null)
                {
                    SetFeedBack(string.Format("O termo '{0}' foi adicionado com sucesso.", inserted.Term), Messages.FeedBackType.success);
                }
                else
                {
                    SetFeedBack(string.Format("Ocorreu um erro ao adicionar o termo '{0}'.", inserted.Term), Messages.FeedBackType.error);
                }
                GetAllBlacklistTerms();
            }
            else
            {
                SetFeedBack("Não é possível inserir termos vazios.", Messages.FeedBackType.info);
            }
            
        }

        protected void RepeaterChangePage_Command(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("goPage"))
            {
                int pageSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out pageSelected))
                {
                    CurrentPage = pageSelected;
                }
            }
        }

        private void BuildPagination()
        {
            DtPages.Clear();
            if (blackListSource.Count > PageSize)
            {
                int intermediateCount = 0;
                while (intermediateCount < blackListSource.Count)
                {
                    int pageNr = intermediateCount / PageSize + 1;

                    DataRow dr = DtPages.NewRow();
                    dr["Class"] = (pageNr == CurrentPage ? "current" : string.Empty);
                    dr["PageNumber"] = pageNr;
                    DtPages.Rows.Add(dr);

                    intermediateCount += PageSize;
                }

                paginationList.DataSource = DtPages;
                paginationList.DataBind();
            }
        }

        private void GetAllBlacklistTerms()
        {
            blackListSource.Clear();
            blackListSource.AddRange(_srv.GetAll());
        }

        private void FillBlacklistTermsPages()
        {
            int intermCount = ((CurrentPage) * PageSize > blackListSource.Count) ? (blackListSource.Count - (CurrentPage - 1) * PageSize) : PageSize;
            blacklistGridView.DataSource = blackListSource.GetRange((CurrentPage - 1) * PageSize, intermCount);
            blacklistGridView.DataBind();
        }

        private void SetFeedBack(string htmlMessage, Messages.FeedBackType fType)
        {
            feedbackPanel.InnerHtml = htmlMessage;
            feedbackPanel.Attributes.Add("class", fType.ToString());
        }
    }
}